package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.mapper.VipServiceConfigMapper;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.atguigu.tingshu.user.strategy.ProcessPaidRecord;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <a href="https://www.shallowrecall.top/">Recall`Blog</a></br>
 * <a href="https://github.com/ShallowRecall">GitHub</a>
 *
 * @author Recall
 * @createTime 2025/06/12 00:50
 **/
@Service("1002")
@Slf4j
public class TrackTypePaidRecord implements ProcessPaidRecord {
    @Autowired
    private UserPaidTrackService userPaidTrackService;

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Override
    public void processDiffItemTypePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        String orderNo = userPaidRecordVo.getOrderNo();
        Long userId = userPaidRecordVo.getUserId();
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();

        // 1.幂等性校验（检查该订单是否已经在流水表中 如果在 不用保存 反之才保存）
        LambdaQueryWrapper<UserPaidTrack> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPaidTrack::getOrderNo, orderNo);
        wrapper.eq(UserPaidTrack::getUserId, userId);
        UserPaidTrack userPaidTrack = userPaidTrackService.getOne(wrapper);
        if (userPaidTrack != null) {
            log.error("该声音类型的流水已经记录过");
            return;
        }

        Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfoByTrackId(itemIdList.get(0));
        AlbumInfo albumInfoResultData = albumInfoResult.getData();
        Assert.notNull(albumInfoResultData, "远程调用专辑微服务获取专辑信息失败");

        // 2.保存流水
        List<UserPaidTrack> userPaidTrackList = itemIdList.stream().map(trackId -> {
            UserPaidTrack userPaidTrack1 = new UserPaidTrack();
            userPaidTrack1.setOrderNo(orderNo);
            userPaidTrack1.setUserId(userId);
            userPaidTrack1.setAlbumId(albumInfoResultData.getId());
            userPaidTrack1.setTrackId(trackId);
            return userPaidTrack1;
        }).collect(Collectors.toList());

        boolean b = userPaidTrackService.saveBatch(userPaidTrackList);
        log.info("记录声音流水：{}", b ? "success" : "fail");
    }
}
